// 加载执行记录列表
function loadRecordList(page = 1) {
    currentPage = page;
    
    const searchQuery = $('#search-input').val();
    
    $.ajax({
        url: '/record/data',
        method: 'GET',
        data: {
            search: searchQuery,
            filter: currentFilter,
            page: page,
            per_page: perPage
        },
        success: function(response) {
            renderRecordList(response.records);
            renderPagination(response.pagination);
        },
        error: function(error) {
            console.error('加载执行记录列表失败:', error);
            showToast('error', '加载执行记录列表失败');
        }
    });
}

// 渲染执行记录列表
function renderRecordList(records) {
    console.log('渲染执行记录列表:', records);
    const recordList = $('#record-list');
    recordList.empty();
    
    if (records.length === 0) {
        recordList.append('<tr><td colspan="9" class="text-center">暂无数据</td></tr>');
        return;
    }
    
    records.forEach(record => {
        const statusBadge = getStatusBadge(record.status);
        const triggerBadge = getTriggerBadge(record.trigger);
        const duration = record.duration ? formatDuration(record.duration) : '-';
        
        recordList.append(`
            <tr data-id="${record.id}">
                <td>${record.id}</td>
                <td>${record.scene_name || '-'}</td>
                <td>${record.environment_name || '-'}</td>
                <td>${statusBadge}</td>
                <td>${triggerBadge}</td>
                <td>${record.start_time || '-'}</td>
                <td>${record.end_time || '-'}</td>
                <td>${duration}</td>
                <td>
                    <button class="btn btn-sm btn-info view-record" data-id="${record.id}">
                        <i class="bi bi-eye"></i>
                    </button>
                    <button class="btn btn-sm btn-primary rerun-record" data-id="${record.id}">
                        <i class="bi bi-arrow-repeat"></i>
                    </button>
                </td>
            </tr>
        `);
    });
}

// 获取状态对应的徽章
function getStatusBadge(status) {
    const badgeClass = {
        'success': 'bg-success',
        'failed': 'bg-danger',
        'running': 'bg-primary',
        'pending': 'bg-secondary'
    };
    
    const statusText = {
        'success': '成功',
        'failed': '失败',
        'running': '运行中',
        'pending': '等待中'
    };
    
    return `<span class="badge ${badgeClass[status] || 'bg-secondary'}">${statusText[status] || status}</span>`;
}

// 获取触发方式对应的徽章
function getTriggerBadge(trigger) {
    const badgeClass = {
        'manual': 'bg-info',
        'scheduled': 'bg-warning',
        'webhook': 'bg-primary'
    };
    
    const triggerText = {
        'manual': '手动',
        'scheduled': '定时',
        'webhook': 'Webhook'
    };
    
    return `<span class="badge ${badgeClass[trigger] || 'bg-secondary'}">${triggerText[trigger] || trigger}</span>`;
}

// 格式化持续时间
function formatDuration(duration) {
    if (duration < 1000) {
        return `${duration}ms`;
    } else if (duration < 60000) {
        return `${(duration / 1000).toFixed(2)}s`;
    } else {
        const minutes = Math.floor(duration / 60000);
        const seconds = ((duration % 60000) / 1000).toFixed(2);
        return `${minutes}m ${seconds}s`;
    }
}

// 渲染分页
function renderPagination(pagination) {
    const paginationEl = $('#pagination ul');
    paginationEl.empty();
    
    // 更新分页信息
    const start = (pagination.current_page - 1) * pagination.per_page + 1;
    const end = Math.min(pagination.current_page * pagination.per_page, pagination.total_items);
    $('#pagination-info').text(`显示 ${start}-${end} 条，共 ${pagination.total_items} 条`);
    
    // 上一页
    paginationEl.append(`
        <li class="page-item ${pagination.current_page === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${pagination.current_page - 1}">上一页</a>
        </li>
    `);
    
    // 页码
    for (let i = 1; i <= pagination.total_pages; i++) {
        if (
            i === 1 || 
            i === pagination.total_pages || 
            (i >= pagination.current_page - 2 && i <= pagination.current_page + 2)
        ) {
            paginationEl.append(`
                <li class="page-item ${i === pagination.current_page ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `);
        } else if (
            i === pagination.current_page - 3 || 
            i === pagination.current_page + 3
        ) {
            paginationEl.append(`
                <li class="page-item disabled">
                    <a class="page-link" href="#">...</a>
                </li>
            `);
        }
    }
    
    // 下一页
    paginationEl.append(`
        <li class="page-item ${pagination.current_page === pagination.total_pages ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${pagination.current_page + 1}">下一页</a>
        </li>
    `);
}

// 查看执行记录详情
function viewRecord(recordId) {
    $.ajax({
        url: `/record/${recordId}`,
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const record = response.record;
                
                // 填充基本信息
                $('#record-id').text(record.id);
                $('#record-scene').text(record.scene_name || '-');
                $('#record-environment').text(record.environment_name || '-');
                $('#record-status').html(getStatusBadge(record.status));
                $('#record-trigger').html(getTriggerBadge(record.trigger));
                $('#record-start-time').text(record.start_time || '-');
                $('#record-end-time').text(record.end_time || '-');
                $('#record-duration').text(record.duration ? formatDuration(record.duration) : '-');
                
                // 填充变量
                renderJsonViewer('#record-variables', record.variables || {});
                
                // 填充执行步骤
                renderRecordSteps(response.steps);
                
                // 设置重新执行按钮
                $('#rerun-btn').data('id', record.id);
                
                // 显示模态框
                $('#detailModal').modal('show');
            } else {
                showToast('error', response.message || '获取执行记录详情失败');
            }
        },
        error: function(error) {
            console.error('获取执行记录详情失败:', error);
            showToast('error', '获取执行记录详情失败');
        }
    });
}

// 渲染执行步骤
function renderRecordSteps(steps) {
    const stepsContainer = $('#record-steps');
    stepsContainer.empty();
    
    if (steps.length === 0) {
        stepsContainer.append('<div class="alert alert-info">暂无执行步骤</div>');
        return;
    }
    
    const stepsList = $('<div class="list-group"></div>');
    
    steps.forEach(step => {
        stepsList.append(renderStepItem(step));
    });
    
    stepsContainer.append(stepsList);
}

// 渲染步骤项
function renderStepItem(step) {
    const statusClass = {
        'success': 'list-group-item-success',
        'failed': 'list-group-item-danger',
        'running': 'list-group-item-primary',
        'pending': 'list-group-item-secondary',
        'skipped': 'list-group-item-warning'
    };
    
    const duration = step.duration ? formatDuration(step.duration) : '-';
    
    const stepItem = $(`
        <div class="list-group-item ${statusClass[step.status] || ''}" data-id="${step.id}">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="mb-1">${step.name || `步骤 ${step.id}`}</h5>
                <span class="badge ${getStatusBadgeClass(step.status)}">${getStatusText(step.status)}</span>
            </div>
            <p class="mb-1">类型: ${getStepTypeText(step.type)}</p>
            <small>开始时间: ${step.start_time || '-'} | 结束时间: ${step.end_time || '-'} | 耗时: ${duration}</small>
            
            <div class="mt-2">
                <button class="btn btn-sm btn-outline-secondary toggle-step-details" data-bs-toggle="collapse" data-bs-target="#step-details-${step.id}">
                    <i class="bi bi-chevron-down"></i> 详情
                </button>
            </div>
            
            <div class="collapse mt-3" id="step-details-${step.id}">
                <div class="card card-body">
                    <ul class="nav nav-tabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="request-tab-${step.id}" data-bs-toggle="tab" data-bs-target="#request-${step.id}" type="button" role="tab">请求</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="response-tab-${step.id}" data-bs-toggle="tab" data-bs-target="#response-${step.id}" type="button" role="tab">响应</button>
                        </li>
                        ${step.error ? `
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="error-tab-${step.id}" data-bs-toggle="tab" data-bs-target="#error-${step.id}" type="button" role="tab">错误</button>
                        </li>
                        ` : ''}
                    </ul>
                    <div class="tab-content p-3 border border-top-0">
                        <div class="tab-pane fade show active" id="request-${step.id}" role="tabpanel">
                            <div id="step-request-${step.id}"></div>
                        </div>
                        <div class="tab-pane fade" id="response-${step.id}" role="tabpanel">
                            <div id="step-response-${step.id}"></div>
                        </div>
                        ${step.error ? `
                        <div class="tab-pane fade" id="error-${step.id}" role="tabpanel">
                            <pre class="text-danger">${step.error}</pre>
                        </div>
                        ` : ''}
                    </div>
                </div>
                
                ${step.children && step.children.length > 0 ? `
                <div class="mt-3">
                    <h6>子步骤</h6>
                    <div class="ps-4 border-start">
                        ${renderChildSteps(step.children)}
                    </div>
                </div>
                ` : ''}
            </div>
        </div>
    `);
    
    // 渲染请求和响应的JSON查看器
    setTimeout(() => {
        renderJsonViewer(`#step-request-${step.id}`, step.request || {});
        renderJsonViewer(`#step-response-${step.id}`, step.response || {});
    }, 100);
    
    return stepItem;
}

// 渲染子步骤
function renderChildSteps(children) {
    const childrenHtml = [];
    
    children.forEach(child => {
        childrenHtml.push(renderStepItem(child).prop('outerHTML'));
    });
    
    return childrenHtml.join('');
}

// 获取步骤类型文本
function getStepTypeText(type) {
    const typeText = {
        'api': 'API请求',
        'script': '脚本',
        'condition': '条件判断',
        'loop': '循环'
    };
    
    return typeText[type] || type;
}

// 获取状态文本
function getStatusText(status) {
    const statusText = {
        'success': '成功',
        'failed': '失败',
        'running': '运行中',
        'pending': '等待中',
        'skipped': '已跳过'
    };
    
    return statusText[status] || status;
}

// 获取状态徽章类
function getStatusBadgeClass(status) {
    const badgeClass = {
        'success': 'bg-success',
        'failed': 'bg-danger',
        'running': 'bg-primary',
        'pending': 'bg-secondary',
        'skipped': 'bg-warning'
    };
    
    return badgeClass[status] || 'bg-secondary';
}

// 渲染JSON查看器
function renderJsonViewer(selector, data) {
    $(selector).empty();
    
    if (!data || Object.keys(data).length === 0) {
        $(selector).text('无数据');
        return;
    }
    
    const jsonViewer = new JSONViewer();
    $(selector).append(jsonViewer.getContainer());
    jsonViewer.showJSON(data);
}

// 重新执行记录
function rerunRecord(recordId) {
    $.ajax({
        url: `/record/${recordId}/rerun`,
        method: 'POST',
        success: function(response) {
            if (response.success) {
                showToast('success', response.message || '已开始重新执行');
                $('#detailModal').modal('hide');
                loadRecordList(currentPage);
            } else {
                showToast('error', response.message || '重新执行失败');
            }
        },
        error: function(error) {
            console.error('重新执行失败:', error);
            showToast('error', '重新执行失败');
        }
    });
}